//app.js

var QQMapWX = require('./utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;

App({
  data : {
    recorderManager : null,
    innerAudioContext : null
  },
  onLoad: function () {

  },

  onLaunch: function () {

    var that = this;

    this.refresh();
    
    // 检测用户开启权限
    this.checkAuthUserLocation();

    // 检查session是否过期
    wx.checkSession({
      success: function (res) {
        //session_key 未过期，并且在本生命周期一直有效
        that.getSession();
      },
      fail: function (res) {
        // 已经失效，需要重新执行登录流程
        that.getSession();
      }
    });

    that.getUserInfo();
    
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          that.getUserInfo();
        }
      }
    });
  }
  /**
   * 获取用户信息并保存
   */
  , getUserInfo : function() {
    var that = this;
    wx.getUserInfo({
      success: res => {
        wx.request({
          url: that.globalData.apiUrl + 'user/addUser',
          method: 'POST',
          header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
          },
          data: {
            encryptedData: res.encryptedData,
            iv: res.iv,
            rawData: res.rawData,
            signature: res.signature
          },
          success: function (res) {

          },
          fail : function(res) {
            that.reportError(res.errMsg, 'user/addUser');
          }
        });
        // 可以将 res 发送给后台解码出 unionId
        that.globalData.userInfo = res.userInfo

        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (that.userInfoReadyCallback) {
          that.userInfoReadyCallback(res)
        }
      }
    });
  }
  /**
   * 设置默认地址-北京市
   */
  ,getDefaultPosition : function() {
    var that = this;
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'JSIBZ-FS5WP-O26D2-VCEJK-AKX4Q-IGBTV'
    });

    //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: that.globalData.latitude,
        longitude: that.globalData.longitude,
      },
      success: function (addressRes) {

        if (addressRes.status == 0) {
          that.globalData.position = addressRes.result.formatted_addresses.recommend;
        }
        
        if (that.positionReadyCallback) {
          var lo = new Object();
          lo.position = addressRes.result.formatted_addresses.recommend;
          lo.latitude = that.globalData.latitude;
          lo.longitude = that.globalData.longitude;
          that.positionReadyCallback(lo);
        }
      }
    });
     
  },
  /**
   * 调用腾讯地图设置用户位置信息
   */
  getUserPosition:function() {
    var that = this;
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'JSIBZ-FS5WP-O26D2-VCEJK-AKX4Q-IGBTV'
    });

    // 获取当前位置坐标
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.globalData.latitude = res.latitude;
        that.globalData.longitude = res.longitude;

        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            if (addressRes.status == 0) {
              that.globalData.position = addressRes.result.formatted_addresses.recommend;
            }
      
            if (that.positionReadyCallback) {
              var lo = new Object();
              lo.position = addressRes.result.formatted_addresses.recommend;
              lo.latitude = res.latitude;
              lo.longitude = res.longitude;
              that.positionReadyCallback(lo)
            }
          }
        });
      },
      fail : function(res) {
        that.reportError(res.errMsg, 'wx.getLocation');
      }
    });
  }
  /**
   * 检测用户是否开启地理位置权限
   */
  , checkAuthUserLocation : function() {
    var that = this;
    wx.getSetting({
      success: res => {
        var content = '';
        if (res.authSetting['scope.userLocation'] == true) {
          // 用户已授权，可以直接调用相关 API
          // 调用腾讯地图设置用户初始化位置
          that.getUserPosition();
        } else if (res.authSetting['scope.userLocation'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          that.showModelUserLocation();
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          wx.authorize({
            scope: 'scope.userLocation',
            success(res) {
              that.getUserPosition();
            },fail(res) {
              that.showModelUserLocation();
            }
          });
        } 
      }
    });
  }
  /**
   * 展示提醒用户开启地理位置权限
   */
  , showModelUserLocation:function() {
    var that = this;
    wx.showModal({
      title: '温馨提醒',
      content: '拼单么需要使用你的地理位置才能正确找到你周围拼单信息',
      showCancel: true,
      confirmText: '去设置',
      success: function (res) {
        if (res.confirm) {
          that.globalData.reload_position = 1;
          that.globalData.position = '';
          wx.openSetting({
            success: (res) => {
              res.authSetting = {
                "scope.userInfo": true,
                "scope.userLocation": true,
                "scope.record": true
              }
            }
          });
        } else if (res.cancel) {
          that.getDefaultPosition();
        }
      }
    });
  }
  /**
   * 检测用户是否已开启录音权限
   */
  , checkAuthRecord:function() {
    var that = this;
    wx.getSetting({
      success: res => {
        var content = '';
        if (res.authSetting['scope.record'] == true) {
          // 用户已授权，可以直接调用相关 API
        } else if (res.authSetting['scope.record'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          that.showModelRecord();
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          wx.authorize({
            scope: 'scope.record',
            success(res) {
            }, fail() {
              that.showModelRecord();
            }
          });
        }
      }
    });
  }
  /**
   * 提示用户需要开启录音权限
   */
  , showModelRecord: function () {
    var that = this;
    wx.showModal({
      title: '温馨提醒',
      content: '拼单么需要使用你的录音功能才能发布语音拼单信息',
      showCancel: true,
      confirmText: '去设置',
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              res.authSetting = {
                "scope.userInfo": true,
                "scope.userLocation": true,
                "scope.record": true
              }
            }
          });
        } else if (res.cancel) {
        }
      }
    });
  }
  /**
   * 检测用户是否已经登录，并且是否授权
   */
  ,checkAuthUserInfo:function(from_url) {
    var that = this;
    this.globalData.from_url = from_url;

    wx.request({
      url: that.globalData.apiUrl + 'user/getUserInfo',
      header: {
        'content-type': 'application/json',
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      success: function (res) {
        if (res.data.code == 10000) {
          if (from_url == '/pages/my/my') {
            wx.switchTab({
              url: from_url
            });
          } else if (from_url == '/pages/toAction/toAction') {
            wx.navigateTo({
              url: from_url
            })
          } else if (from_url == '') {
            wx.navigateTo({
              url: '/pages/index/index'
            });
          }
          return false;
        }  else {
          that.showModelUserInfo();
        }
      },
      faile:function(res) {
        that.showModelUserInfo();
      }
    });
  }
  /**
   * 展示用户信息授权模块
   */
  , showModelUserInfo : function() {
    var that = this;
    wx.showModal({
      title: '微信授权',
      content: '拼单么申请获取您的公开信息（昵称、头像等）',
      showCancel: true,
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        } else if (res.cancel) {
          console.log('getuserinfo cancel');
        }
      }
    });
  }
  /**
   * 检测用户授权模块是否开启
   */
  , checkAuth:function() {
    wx.getSetting({
      success: res => {
        var content = '';
        if (!res.authSetting['scope.userInfo']) {
          content += '用户信息';
        }
        if (!res.authSetting['scope.userLocation']) {
          if (content.length > 0) content += "、";
          content += '地理位置';
        }
        if (!res.authSetting['scope.record']) {
          if (content.length > 0) content += "、";
          content += '录音功能';
        }

        if (content.length > 0 && false) {
          wx.showModal({
            title: '微信授权',
            content: '拼单么申请获取您的' + content + '才能找到您附近的拼单信息',
            showCancel: false,
            confirmText: '去设置',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    res.authSetting = {
                      "scope.userInfo": true,
                      "scope.userLocation": true,
                      "scope.record": true
                    }
                  }
                });
              }
            }
          });
        }
      }
    });
  }

  , getSession:function() {
    var that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // 发起网络请求
        wx.request({
          url: that.globalData.apiUrl + 'user/onLogin',
          method:"GET",
          header: {
            "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
          },
          data: {
            code: res.code
          },
          success: function (res) {
            if (res.data.code == 10000) {
              wx.setStorageSync("sessionID", res.data.message.session_id);
            } else if(res.data.code != 99999) {
              wx.setStorageSync("sessionID", '');
            }
          }, fail(res) {
            that.reportError(res.errMsg, 'user/onLogin');
          }
        })
      }
    });
  }
  /**
   * 刷新session接口
   */
  , refresh : function() {
    var that = this;
    setInterval(that.getSession, 1200000);
  },

  /**
   * 初始化录音管理
   */
  initRecorderManager : function() {
    var that = this;
    this.data.recorderManager = wx.getRecorderManager();
    this.data.innerAudioContext = wx.createInnerAudioContext();
  },
  /**
  * 提示
  */
  tip: function (msg, status = 'success') {
    wx.showToast({
      title: msg,
      icon: status,
      duration: 1000
    });
  }
  
  /**
   * 错误报告
   */
  , reportError : function(message, api = '') {
    wx.request({
      url: this.globalData.apiUrl + 'report/requestError',
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      data: {
        api : api,
        message: message
      },
      success: function (res) {

      }, fail(res) {

      }
    })
  }

  /**
   * formId
   */
  , formIdSubmit : function(e) {
    
    var formId = e.detail.formId;
    if (typeof (formId) != "undefined" && formId != '' && formId != 'the formId is a mock one') {
      wx.request({
        url: this.globalData.apiUrl + 'user/formId',
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
        },
        data: {
          form_id: formId,

        }, success: function (res) {

        }, fail: function (res) {
          that.reportError(res.errMsg);
        }
      });
    }
  }
  /**
   * 全局变量
   */
  , globalData: {
    imagePath : '/images/default',
    userInfo: null,
    position: "",
    reload_position : 0,
    latitude: 40.05307,
    longitude: 116.306243,
    from_url: '',
    // apiUrl: "http://api.pindan.me/",
    // staticApiUrl: "http://api.pindan.me/static/images/",
    // staticVoiceUrl: "https://api.pindan.me/static/voice/"
    apiUrl: "https://api.pd.cikewang.com/",
    staticApiUrl: "https://api.pd.cikewang.com/static/images/",
    staticVoiceUrl: "https://api.pd.cikewang.com/static/voice/"
  }
}); 